import sys
import asyncio
import websocket
import threading
import time
import random


SUCCESS = []
FAILED = []
statistics = {}
threads = []


def on_open(ws):
    print("Successfully connected to WebSocket server")

def on_close(ws):
    print("Connection closed")

def random_select():
    ports = [8081,8083,8084,8085,8086]
    return random.choice(ports)

def connect_websocket(ws_client):
    #uri = f"ws://10.240.51.97:8088/ws/cmdset/?hostname={ws_client}"  # 替换为实际的WebSocket服务器地址
    port = random_select()
    if not statistics.get(port):
        statistics[port] = 1
    else:
        statistics[port] = statistics[port] +1
    uri = f"ws://10.240.51.97:{port}/cmdset/?hostname={ws_client}"  # 替换为实际的WebSocket服务器地址
    #uri = f"ws://10.240.51.97:8083/cmdset/?hostname={ws_client}"  # 替换为实际的WebSocket服务器地址
    # while True:
    # ws = websocket.WebSocketApp(uri, on_open=on_open, on_close=on_close)
    # ws.run_forever()
    # ws.close()
    # print(uri)

    ws = websocket.WebSocket()
    ws.connect(uri)
    # ws.send("Hello, server!")
    # response = ws.recv()
    # print(f"Received from server: {response}")
    # print(ws.connected)
    if ws.connected:
        #print(f"Successfully connected to WebSocket server: {ws_client}")
        SUCCESS.append(ws_client)
        time.sleep(30)
    else:
        #print("Failed to connect to WebSocket server")
        FAILED.append(ws_client)
    ws.close()


def main(idx,num):
    #threads = []
    for i in range(num):  # 创建100个客户端连接
        ws_client = f'main_{idx}_test_{i}'
        thread = threading.Thread(target=connect_websocket, args=(ws_client,))
        thread.start()
        threads.append(thread)
    #for thread in threads:
    #    thread.join()


if __name__ == "__main__":
    if len(sys.argv) > 1:
        idx = sys.argv[1]
    else:
        print('xxxxxxxxxxxx')
        exit(0)
    num = 1
    main(idx, num)
    #for i in range(1):
    #    main(i,num)

    #print(f'success:\n    {len(SUCCESS)}   {SUCCESS}')
    #print(f'Failed:\n    {len(FAILED)}    {FAILED}')
    #print(f'statistics:\n        {statistics}')

    for thread in threads:
        thread.join()
    print(f'main {sys.argv[1]} : \n success:\n    {len(SUCCESS)}   {SUCCESS} \n statistics:\n        {statistics}')
    #print(f'main : {sys.argv[1]} \n Failed:\n    {len(FAILED)}    {FAILED}')
    #print(f'main : {sys.argv[1]} \n statistics:\n        {statistics}')

